import requests
from wechat_index.utils import generate_date


class WechatIndex:
    """
    :param search_key: 调用API时的认证参数，需要通过打开小程序后，查看请求的search_key参数
    """

    def __init__(self, search_key, openid):
        self.search_key = search_key
        self.openid = openid

    def _deserialize_wxindex_string(self, wxindex_string):
        """
        该函数会解析指数的字符串为列表
        :param wxindex_string: 需要转换成列表的指数字符串
        例子：
        "384648,380067,373172,505561,540113,601451..." 共90个
        :return: 包含指数数据的列表
        例子：
        [384648,380067,373172,505561,540113,601451] 共90 个
        """
        items = None

        if wxindex_string:
            items = wxindex_string.split(',')
        else:
            return

        return items

    def query_wxindex(self, keywords):
        """
        该函数调用微信的小程序API查询对应的关键词的指数
        :param keyword: 字符串，查询单个关键词
        :param keyword_list: 字符串列表，查询多个关键词
        :return: 返回结果
        例子：
        {'index_list': [{'keyword': 'python', 'data': {'2018-04-05': '384648', ...}]
        """
        headers = {
            "charset": "utf-8",
            "Accept-Encoding": "gzip",
            "referer": "https",
            "content-type": "application/json",
            "User-Agent": "Mozilla/5.0 (Linux; Android 7.0; MI 5s Plus Build/NRD90M; wv) "
                        "AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/53.0.2785.143 "
                        "Crosswalk/24.53.595.0 XWEB/155 MMWEBSDK/21 Mobile Safari/537.36 "
                        "MicroMessenger/6.6.7.1321(0x26060736) NetType/4G Language/zh_CN "
                        "MicroMessenger/6.6.7.1321(0x26060736) NetType/WIFI Language/zh_CN",
            "Host": "search.weixin.qq.com",
            "Connection": "Keep-Alive"
        }
        api = 'https://search.weixin.qq.com/cgi-bin/searchweb/wxindex/querywxindexgroup'
        group_query_list = []
        wxindex_query_list = []

        params = {
            'gid': '',
            'openid': self.openid,
            'search_key': self.search_key
        }
        if not keywords:
            raise Exception("关键词不能为空")
        

        if isinstance(keywords, str):
            group_query_list.append(keywords)
            wxindex_query_list.append(keywords)

            params['group_query_list'] = ';'.join(group_query_list)
            params['wxindex_query_list'] = ';'.join(wxindex_query_list)

        elif isinstance(keywords, list):
            group_query_list = keywords
            wxindex_query_list = keywords

            params['group_query_list'] = ';'.join(group_query_list)
            params['wxindex_query_list'] = ';'.join(wxindex_query_list)

        result = {
            'errcode': 0,
            'msg': '',
            'index_list': []
        }

        try:
            resp = requests.get(url=api, params=params, headers=headers)
            resp = resp.json()

            errcode = resp['errcode']
            if errcode == 0:
                data = resp.get('data')  # 所有数据
                group_wxindex = data.get('group_wxindex')  # 列表，包含查询词的列表信息
                if group_wxindex:
                    if len(group_wxindex) == 1:
                        index_str = group_wxindex[0].get('wxindex_str')
                        keyword_name = group_wxindex[0].get('query')
                        index_list = self._deserialize_wxindex_string(index_str)
                        index_list.reverse()
                        dates = generate_date()
                        dates.reverse()
                        index_with_date_dict = dict(zip(dates, index_list))
                        tem_dict = {
                            'keyword': keyword_name,
                            'data': index_with_date_dict
                        }
                        result['index_list'].append(tem_dict)

                    # 如果查询多个关键词的话就用这个
                    else:
                        for index in group_wxindex:
                            index_str = index.get('wxindex_str')
                            keyword_name = index.get('query')

                            index_list = self._deserialize_wxindex_string(index_str)
                            dates = generate_date()
                            index_with_date_dict = dict(zip(dates, index_list))
                            tem_dict = {
                                'keyword': keyword_name,
                                'data': index_with_date_dict
                            }
                            result['index_list'].append(tem_dict)

            else:
                result['errcode'] = resp.get('errcode')
                result['msg'] = resp.get('msg')


        except Exception as e:
            result['errcode'] = 1
            result['msg'] = str(e)

        return result

